package org.itboys.mobile.service.mongo.web.business;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemRole;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.admin.entity.lasted.SystemUserRole;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.admin.service.lasted.SystemRoleService;
import org.itboys.admin.service.lasted.SystemUserRoleService;
import org.itboys.admin.service.lasted.SystemUserService;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商户_service
 */
@Service
public class SundayBusinessService extends BaseMongoService<SundayMember> {

    @Autowired
    private SystemUserService userService;
    @Autowired
    private SystemRoleService roleService;
    @Autowired
    private SystemUserRoleService userRoleService;
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private SystemUserService systemUserService;

    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }


    /**
     *新增或修改商户
     * @param business
     * @param imageFile
     */
    public void saveBusiness(SundayMember business,MultipartFile imageFile) throws  Exception{
        //保存主图
        Map<String, String> map = uploadService.uploadSingle(imageFile);
        if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
            business.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
        }
        //默认正常
        Map<String,Object> param =new HashMap<String, Object>();
        if(business.getId()==0l){
            param.put("isDeleted",0);
            param.put("mobile",business.getMobile());
            if(LongUtil.isNotZreo(super.count(param))){
                throw new ErrorException("手机号不能重复");
            }
            //生成默认头像
            business.setImage(NameUtil.getRandomLogo());
            if(StringUtils.isNotEmpty(business.getPassword())){
                business.setPassword(Digests.md5(business.getPassword()));
            }
            //初始化一些状态
            business.setUserType(SundayCommonConstants.user_type_business);
            business.setFirstTjId(0l);
            business.setSecondTjId(0l);
            business.setStatus(SundayCommonConstants.NO);
            business.setUserName(NumberUtil.generateNumber("APP"));
            super.save(business);
            //绑定登陆账号角色
            param.clear();
            param.put("isDeleted",0);
            param.put("name","商户角色");
            List<SystemRole> roles = roleService.list(param);
            if(ListUtil.isNull(roles))return;
            //，2017年9月25日，给商户添加后台登陆账号
            SystemUser user = new SystemUser();
            user.setMobile(business.getMobile());
            user.setUserName(business.getMobile());
            //手机号后6位
            String password=business.getMobile().substring(business.getMobile().length()-6,business.getMobile().length());
            user.setPassword(Digests.md5(password));
            user.setName(business.getNickName());
            user.setIsSuper(SundayCommonConstants.NO);
            user.setStatus(SundayCommonConstants.NO);
            //绑定商户ID
            user.setPlatformMemberId(business.getId());
            userService.save(user);
            //绑定角色
            userRoleService.save(new SystemUserRole(user.getId(),roles.get(0).getId()));
        }else{
            param.put("id !=",business.getId());
            param.put("isDeleted",0);
            param.put("mobile",business.getMobile());
            if(LongUtil.isNotZreo(super.count(param))){
                throw new ErrorException("该手机号已经被注册");
            }
            if(StringUtils.isNotEmpty(business.getPassword())){
                business.setPassword(Digests.md5(business.getPassword()));
            }
            super.updateExceptEmpty(business.getId(),business);
        }

    }
    //查询商户
    public SundayMember findOne(Long id){
        SundayMember business= null;
        if(LongUtil.isNotZreo(id)){
            business=super.getById(id);
        }else{
            if(LongUtil.isNull(id)){
                SystemUser loginUser =systemUserService.getById(AdminSessionHolder.getAdminUserId());
                id=loginUser.getPlatformMemberId();
                business=super.getById(id);
            }else{
                business = new SundayMember();
                business.setId(0l);
            }
        }
        return business;
    }
    /**
     * 重置为默认密码
     * @param id
     */
    public void resetPassword(Long id){
        SundayMember member=super.getById(id);
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("platformMemberId",id);
        List<SystemUser> users = userService.list(param);
        if(ListUtil.isNotNull(users)){
            userService.update(users.get(0).getId(),"password",Digests.md5(SundayCommonConstants.default_password));
        }
    }

    /**
     * 冻结或解冻
     * @param id
     * @param status
     */
    public void change(Long id,Integer status){
        super.update(id,"status",status);
        //2018年3月9日，冻结后台登陆账号
        SundayMember member=super.getById(id);
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("platformMemberId",id);
        List<SystemUser> users = userService.list(param);
        if(ListUtil.isNotNull(users)){
            userService.update(users.get(0).getId(),"status",status);
        }
        //冻结商品

    }
}
